<template>
  <div class="map-box" >
    <div class="detail">
        <van-row>
            <van-col span="12">
                <p>经度：{{point ? point[0] : '-'}}</p>
            </van-col>
            <van-col span="12">
                <p>纬度：{{point ? point[1] : '-'}}</p>
            </van-col>
        </van-row>
        <van-row>
           <p>地址：{{address}}</p>
        </van-row>
    </div>
    <div class="hiddenLogo"></div>
    <div id="amap" class="amap"></div>
  </div> 
</template>

<script>
import { Toast } from 'vant';
export default {
  props: {
    lnglat: {
      type: Array,
      validator: (value) => {
        return value.length === 2
      }
    }
  },
  data () {
    return { address: '', point: this.lnglat }
  },
  mounted () {
    this.init(this.point)
  },
  methods: {

    // 初始化
    init (lnglat) {
      // 地图实例对象 （amap 为容器的id）
      let amap = new AMap.Map('amap', {
        resizeEnable: true,
        zoom: 15
      })
      // 注入插件（定位插件，地理编码插件）
      amap.plugin(['AMap.Geolocation', 'AMap.Geocoder'])
      // 定位
      this.currentPosition(amap, lnglat)
    },

    currentPosition (map, lnglat) {
      if (lnglat) {
        // 有传入坐标点，直接定位到坐标点
        map.setCenter(lnglat)
        this.addMark(map, lnglat)

        // 获取地址
        this.getAddress(lnglat)
      } else {
        // 没有传入坐标点，则定位到当前所在位置
        let geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          zoomToAccuracy: true,     
          buttonPosition: 'RB'
        })
        geolocation.getCurrentPosition((status, result) => {
          if (status === 'complete') {
            let points = [result.position.lng, result.position.lat]
            map.setCenter(points) // 设置中心点
            this.addMark(map, points) // 添加标记

            // 存下坐标与地址
            this.point = points
            this.getAddress(points)
          } else {
            console.log('定位失败', result)
            Toast.fail({
                duration: 3000,     
                message:"定位失败，请打开手机定位，允许海政钉获取定位"
            });
          }
        })
      }
    },

    // 添加标记
    addMark (map, points) {
      let marker = new AMap.Marker({
        map: map,
        position: points,
        draggable: true, // 允许拖动
        cursor: 'move',
        raiseOnDrag: true
      })
      marker.on('dragend', (e) => {
        let position = marker.getPosition()

        // 存下坐标与地址
        this.point = [position.lng, position.lat]
        this.getAddress([position.lng, position.lat])
      })
    },
    // 根据坐标返回地址(逆地理编码)
    getAddress (points) {
      let geocoder = new AMap.Geocoder({ radius: 1000 })
      geocoder.getAddress(points, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          this.address = result.regeocode.formattedAddress
          this.commit();
        }
      })
    },
    commit(){
      this.$emit('location', this.point, this.address)
    }
  }
}
</script>

<style lang="scss" scoped>
.map-box {
    box-sizing: border-box;
    background-color: #fff;
    padding: .15rem .15rem;   
    position:relative;
    .amap {
        width: 100%;    
        height: 6rem;
    }
    .hiddenLogo{
        position:absolute;
        bottom:0;
        left:0;
        z-index:300;
        height:1rem;
        width:100%;
        background:#fff;
    }
    .detail {
        width: 100%;    
        min-height: 1rem;
        text-align:left;
        background-color: #fff;
        padding: 0rem .15rem;   
        border-left: .05rem solid #eee;
        box-sizing: border-box;
        word-wrap: break-word;
        margin-bottom: .2rem;
        p{
            height:.6rem;
            line-height:.6rem;
        }
    }
    .btnmap {
        width: 100%;
        margin: .3rem 0 0 0;
        padding: 5px 0;
        color: #fff;
        cursor: pointer;
        background-color: #409eff;
        border: none;    
        border-radius: 3px;
        &:hover {
            background-color: #66b1ff;
        }
    }
}
</style>